package util;



import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 *   注意这时在的key，只能是16个字符，也就是128位。如果要用更长的密钥（如32位），需要下载新的jar包，更换
 //默认Jdk lib\lib\security 下需的两个包
 // local_policy.jar

 US_export_policy.jar

 默认 Java 中仅支持 128 位密钥，当使用 256 位密钥的时候，会报告密钥长度错误

 Invalid AES key length
 你需要下载一个支持更长密钥的包。这个包叫做 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6，可以从这里下载，
 下载地址：https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

 **/

public class AESUtils {

    public static void main(String[] args) throws Exception {
        System.out.println(MyUtil.createRandomCharData(16));
        String key="3p1Wo019tz09G709";
      //key=MyUtil.createRandomCharData(16);
//        String key="d0c7c027d448186590d31c7908004500";
        /*String str="{\n" +
                "\t\"mcht_no\": \"0001000F0425230\",\n" +
                "\t\"terminal_no\": \"61178709\",\n" +
                "\t\"appid\": \"YUNJIA_0JZi0FdXRo3H7O5bYPfMK5Ad\",\n" +
                "\t\"orderno\": \"21e12e12wqwqwqw\",\n" +
                "\t\"amount\": \"0.01\",\n" +
                "\t\"frontCallback\": \"http: //www.kunteng.org.cn/\"\n" +
                "}";

        String en = aesEncrypt(str,key);

        System.out.println(en);

        System.out.println("====");
*/
        System.out.println(aesDecrypt( "9VbR8dDcgzIoQO01YtX3kk+6wY88X3CiQe2wj+0B08pk/1Zc4tCb+pbJVjw2kSOD",key));

    }

    public static String aesEncrypt(String str, String key)  {
        if(str != null && key != null) {
            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(1, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
                byte[] bytes = cipher.doFinal(str.getBytes("utf-8"));

                return (new Base64()).encodeToString(bytes);
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

    public static String aesDecrypt(String str, String key)   {
        if(str != null && key != null) {
            try {
                Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                cipher.init(2, new SecretKeySpec(key.getBytes("utf-8"), "AES"));
                byte[] bytes = (new Base64()).decode(str);
                bytes = cipher.doFinal(bytes);
                return new String(bytes, "utf-8");
            }catch (Exception e){
                e.printStackTrace();
            }
           return null;
        } else {
            return null;
        }
    }

}
